<?php


namespace app\common\validate;


class RequestCheckValidate extends BaseValidate
{
    protected $rule = [
        'time' => 'require|integer|length:10|checkTime',
        'sign' => 'require|checkSign',
        'appid' => 'require',
        'secret' => 'require'
    ];

    protected $field = [
        'time' => '时间',
        'sign' => '签名',
        'appid' => 'appid',
        'secret' => '秘钥'
    ];

    protected $scene = [
        'login' => ['appid','secret'],
        'check' => ['time','sign'],
    ];

    /**
     * 检测接口请求时间
     * @Author zengxin(573908667@qq.com)
     * @param $value
     * @return string
     */
    protected function checkTime($value)
    {
        if(abs(time()-intval($value)) > 3){
            return '请求超时，请重新请求';
        }
        return true;
    }

    /**
     * 校验签名
     * @Author zengxin(573908667@qq.com)
     * @param $value
     * @param $args
     * @param $data
     * @return string
     */
    protected function checkSign($value,$args,$data)
    {
        unset($data['sign']);

        $sign = base64_decode($value);

        ksort($data);

        $check_sign = str_replace('&amp;','&',http_build_query($data));

        if(md5($check_sign) != $sign){
            return '签名错误';
        }

        return true;
    }
}